<?php
require_once dirname(dirname(dirname(__FILE__))) . '/init.php';
/**
 * 特采自动作废程序：
 * 每天凌晨5点之后查找特采申请列表中，采购状态为空、待采购、部分采购的且最迟回货时间在当前日期之前的申请数据，进行作废操作
 * @author sundongdong
 * @date 2016-09-29
 */
class AutoCloseSpecialPurchase extends Controller_CronJob {
	public function run() {
		// 数据库
		$db = Model_Db::getInstance();
		$wdb = Model_Db::getInstance('write_db');
		// 记录执行时间和执行条数
		$time = time();
		$item = 0;
		$fail = 0;
		$user_id = $db->fetchOne("SELECT user_id from s_user where user_name=:name",['name'=>'SYSTEM']);
		// 找出最迟回货时间是昨天的，且采购状态为待采购和未采购的特采数据
		$sql = 'SELECT id,goods_sn FROM p_special_purchase WHERE datediff(current_date,latest_time) = 1 AND purchase_status NOT IN (1,4)';
		$result = $db->fetchAll($sql);
		foreach ($result as $special) {
			// 更改数据
			$update = [];
			$update['purchase_status'] = 4;
			$update['examine_status'] = 8;
			$update['update_time'] = date('Y-m-d H:i:s');
			$update['examine_user'] = 'SYSTEM';
			// 审核数据
			$examine_data = [];
			$examine_data['psd_id'] = $special['id'];
			$examine_data['examine_type'] = 8;
			$examine_data['user_id'] = $user_id;
			$examine_data['examine_username'] = 'SYSTEM';
			$examine_data['examine_reason'] = '超时系统自动作废';
			$examine_data['examine_time'] = date('Y-m-d H:i:s');
			$examine_data['cancel_date'] = date('Y-m-d H:i:s');
			try {
				$wdb->beginTransaction();
				$wdb->update('p_special_purchase', $update, 'id='.$special['id']);
				$wdb->insert('p_special_purchase_data_exmaine', $examine_data);
				$wdb->commit();
				$item++;
			} catch (Exception $e) {
				$fail++;
				$wdb->rollBack();
				$this->log->record("SKU: ".$special['goods_sn'].$e->getMessage(), Log::ERR);
			}
		}
		$string = '执行时间：【'.(time()-$time).'s】;作废【'.$item.'】条;失败【'.$fail.'】条';
		exit($string);
	}
}

$controller = new AutoCloseSpecialPurchase();
$controller->run();